package com.demo.modules.comm.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.common.base.R;
import com.demo.common.enums.REnum;
import com.demo.modules.sys.entity.SysUserEntity;
import com.demo.modules.sys.service.ShiroService;
import com.demo.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/sys/wechat")
public class WeChatController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ShiroService shiroService;

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Value("${wechat.appid}")
    private String spAppid;

    @Value("${wechat.secret}")
    private String spSecret;

    @GetMapping("/getWechatUserInfo")
    public R getWechatUserInfo(@RequestParam("code") String code) {
        return getUserInfo("https://api.weixin.qq.com/sns/oauth2/access_token", code, appid, secret);
    }

    @GetMapping("/getWechatSpUserInfo")
    public R getWechatSpUserInfo(@RequestParam("code") String code) {
        return getUserInfo("https://api.weixin.qq.com/sns/jscode2session", code, spAppid, spSecret);
    }

    private R getUserInfo(String url, String code, String appid, String secret) {
        try {
            /*请求微信接口*/
            //请求数据
            JSONObject params = new JSONObject();
            params.put("appid", appid);
            params.put("secret", secret);
            params.put("code", code);
            params.put("grant_type", "authorization_code");

            //发送请求
            String resultStr = HttpRequest.get("https://api.weixin.qq.com/sns/oauth2/access_token").form(params).execute().body();
            JSONObject result = JSON.parseObject(resultStr);

            //获取openid
            String openid = result.getString("openid");

            //请求失败（没有获取到openid）
            if (StringUtils.isEmpty(openid)) {
                log.error("获取openid失败：{}", result.toJSONString());
                return R.error(REnum.UN_LOGIN.getCode(), "获取微信授权失败").desc(result);
            }

            //根据openid获取绑定的用户
            SysUserEntity user = sysUserService.queryByOpenId(openid);
            result.put("user", user);

            return R.ok(result);
        } catch (Exception e) {
            log.error("获取openid失败：{}", e.getMessage());
            e.printStackTrace();
            return R.error(REnum.UN_LOGIN.getCode(), "获取微信授权失败").desc(e);
        }
    }
}

